package com.itcast.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itcast.common.res.ResultCode;
import com.itcast.config.AlipayConfig;
import com.itcast.mapper.AddressMapper;
import com.itcast.mapper.OrdersMapper;
import com.itcast.pojo.Address;
import com.itcast.pojo.Orders;
import com.itcast.pojo.dto.OrderDTO;
import com.itcast.service.Ordersservice;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.xml.bind.ValidationException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-06-19
 */
@Slf4j
@Service("ordersservice")
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements Ordersservice {

    @Resource
    private OrdersMapper mapper;

    @Resource
    private AddressMapper addressMapper;

    @Override
    public String insertOrder(OrderDTO dto) throws UnsupportedEncodingException, AlipayApiException {
        Orders orders=new Orders();
        orders.setCount(dto.getShopnum());
        orders.setCreateDate(new Date());
        orders.setTotalPrice(dto.getTotal());
        orders.setGoodsName("坭兴陶");
        orders.setOoid(getOutTradeNo());
        orders.setUserId(dto.getUserId());
        orders.setTotalCount(dto.getShopnum());
        mapper.insert(orders);

        Address address=new Address();
        address.setAddresee(dto.getAddress());
        address.setAddressee(dto.getName());
        address.setPhone(dto.getPhone());
        address.setCreateDate(new Date());
        address.setUserId(dto.getUserId());
        address.setIsDefalut("0");

        addressMapper.insert(address);

        return getPayForm(orders);
    }

    @Override
    public List<Orders> getOrderInfo(String userId) throws ValidationException {
        List<Orders> userInfo = mapper.selectList(new QueryWrapper<Orders>().eq("userId", userId));
        if (CollectionUtils.isEmpty(userInfo)){
            throw new ValidationException(ResultCode.QUERY_FAIL);
        }
        return userInfo;
    }

    private String getPayForm(Orders orders) throws AlipayApiException, UnsupportedEncodingException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no=new String(orders.getOoid().getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount=new String(orders.getTotalPrice().toString().getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject=new String(orders.getGoodsName().getBytes("UTF-8"),"UTF-8");
        //商品描述，可空
        String body=new String(orders.getGoodsName().getBytes("UTF-8"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
//                +"\"timeout_express\":\"2m\"," //订单关闭时间
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\""
//                + ",\"enable_pay_channels\":\"pcredit,moneyFund,debitCardExpress,pcreditpayInstallment\""
//                + ",\"extend_params\":{\"hb_fq_num\":\"3\",\"hb_fq_seller_percent\":\"0\"}"
                + "}");

        //请求
        return alipayClient.pageExecute(alipayRequest).getBody();
    }

    /**
     * 生成支付单号（商家订单号）
     * @return
     */
    public synchronized String getOutTradeNo(){
        Date date=new Date();
        long time = date.getTime();

        String s = DateUtils.formatymdhms.print(LocalDateTime.now())+time;
        log.info("支付单号："+s);
        return s;
    }
}
